<template>
  <el-container>
    <el-header style="background: #fff; border: 1px #e9eef3 solid;">
      <h1 class="title">学生公寓分配管理系统——管理端</h1>
      <el-dropdown style="float: right; margin-top: 30px; margin-right: 50px; font-size: 20px;">
        <span class="el-dropdown-link">
          {{ admin.username }}
          <el-icon class="el-icon--right">
            <arrow-down/>
          </el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </el-header>
    <el-container>'

      <!-- 左侧导航栏 -->
      <el-aside width="200px" style="height: 80%;">
        <el-menu default-active="/admin/bedInfo" router class="el-menu-vertical-demo" default-openeds="{1,2,3}">
          <el-sub-menu index="1">
            <template #title>
              <el-icon>
                <user/>
              </el-icon>
              <span>学生管理</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="/admin">学生信息</el-menu-item>
              <el-menu-item index="/admin/apartment">宿舍分配</el-menu-item>
            </el-menu-item-group>
          </el-sub-menu>
          <el-sub-menu index="2">
            <template #title>
              <el-icon>
                <grid/>
              </el-icon>
              <span>宿舍管理</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="/admin/buildingInfo">楼栋信息</el-menu-item>
              <el-menu-item index="/admin/roomInfo">宿舍信息</el-menu-item>
              <el-menu-item index="/admin/bedInfo">床位信息</el-menu-item>
            </el-menu-item-group>
          </el-sub-menu>
          <view v-if="admin.role==1">
            <el-sub-menu index="3">
              <template #title>
                <el-icon>
                  <stamp/>
                </el-icon>
                <span>人事管理</span>
              </template>
              <el-menu-item-group>
                <el-menu-item index="/admin/adminInfo">宿管信息</el-menu-item>
                <el-menu-item index="/admin/adminPermissions">宿管审核</el-menu-item>
              </el-menu-item-group>
            </el-sub-menu>
          </view>
        </el-menu>
      </el-aside>
      <!-- 右侧内容栏 -->
      <el-main style="background-color: #fff;">
        <el-table
            :data="tableData.slice((pagination.currentPage-1)*pagination.pageSize, pagination.currentPage*pagination.pageSize)"
            style="width: 100%; padding: 8px 8px 0 8px;">
          <el-table-column prop="buildingName" label="宿舍楼" width="250"/>
          <el-table-column prop="roomNum" label="宿舍号" width="250"/>
          <el-table-column prop="bedNum" label="床位号" width="250"/>
          <el-table-column prop="student" label="居住者" width="250">
            <template #default="scope">
              <el-popover effect="light" trigger="hover" placement="bottom">
                <template #default>
                  <p>学号 : {{ scope.row.sid }}</p>
                  <p>姓名 : {{ scope.row.name }}</p>
                  <p>性别 : {{ scope.row.sex == '0' ? '男' : '女' }}</p>
                  <p>专业 : {{ scope.row.major }}</p>
                  <p>班级 : {{ scope.row.classroom }}</p>
                  <p>手机号码 : {{ scope.row.cellphone }}</p>
                </template>
                <template #reference v-if="scope.row.sid">
                  <div class="name-wrapper">
                    <el-tag size="medium">
                      {{ scope.row.name }}
                    </el-tag>
                  </div>
                </template>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="id" label="操作" width="200">
            <template #default="scope">
              <el-popconfirm title="确定删除该床位信息?" @confirm="delRoom(scope.row.id)">
                <template #reference>
                  <el-button size="small" type="danger">删除床位</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <div class="footer">
          <!-- 选择宿舍楼 -->
          <el-select v-model="buildingSelect" style="float: left; margin: 10px;" v-if="admin.role==='1'"
                     @change="buildingChange">
            <el-option :label="item.buildingName" :value="item.buildingName" v-for="(item,index) in buildingList"
                       :key="index"></el-option>
          </el-select>
          <el-select v-model="buildingSelect" style="float: left; margin: 10px;" v-if="admin.role==='2'" disabled>
            <el-option :label="buildingSelect" :value="buildingSelect"></el-option>
          </el-select>
          <!-- 新增宿舍按钮 -->
          <div class="addStuBtn">
            <el-button type="primary" plain @click="addBedDialog">添加床位</el-button>
          </div>
          <!-- 分页 -->
          <el-pagination background layout="prev, pager, next"
                         v-model:currentPage="pagination.currentPage"
                         :page-size="pagination.pageSize"
                         :total="pagination.total"
                         @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </el-main>

      <!-- 新增床位Dialog -->
      <el-dialog
          v-model="addBedDialogVisible" title="添加床位" width="40%">
        <el-form :label-position="left" label-width="10px;" :model="addBedInfo" :rules="rules">
          <el-row :gutter="20">
            <el-col :span="14">
              <el-form-item label="宿舍楼名字" prop="buildingName" label-width="50">
                <el-select v-model="buildingSelect" disabled>
                  <el-option :label="buildingSelect" :value="buildingSelect"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="宿舍号" prop="roomNum" label-width="50">
                <el-input v-model="addBedInfo.roomNum" placeholder="请输入宿舍号" type="number"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="床位号" prop="bedNum" label-width="50">
                <el-input v-model="addBedInfo.bedNum" placeholder="请输入床位号" type="number"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="addBedDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addBed">添加</el-button>
      </span>
        </template>
      </el-dialog>

    </el-container>
  </el-container>


</template>

<script>
import {ElMessage, ElMessageBox} from "element-plus";
import {Stamp, User, Grid, ArrowDown} from '@element-plus/icons'
import axios from 'axios'

export default {
  data() {
    return {
      addBedInfo: {},
      addBedDialogVisible: false,
      buildingSelect: '',
      buildingList: [],
      pagination: {
        total: {
          type: Number
        },
        currentPage: 1,
        pageSize: 8
      },
      admin: {
        username: '',
        role: '',
        buildingName: '',
      },
      tableData: [],
      rules: {
        selecctName: [{
          required: true,
          message: '宿舍楼名字不能为空',
          trigger: 'blur'
        }],
        roomNum: [{
          required: true,
          message: '宿舍号不能为空',
          trigger: 'blur'
        }],
        bedNum: [{
          required: true,
          message: '床位号不能为空',
          trigger: 'blur'
        }],
      }
    }
  },

  methods: {
    /*
      删除床位操作
     */
    delRoom(id) {

      // 封装请求参数
      let postData = new URLSearchParams();
      postData.append("id", id);

      // 通过axios发送请求
      axios.post("/admin/bed/delete", postData)
          .then(function (res) {
            switch (res.data.status) {
              case 10000:
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '删除成功！',
                  type: 'success',
                })
                location.reload();
                break;
              case 10032:
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '该床位有人住，无法删除！',
                  type: 'error',
                })
                break;
            }
          })
    },
    /*
      添加床位操作
     */
    addBed() {
      // 判断床位信息是否为空
      if (!this.buildingSelect || !this.addBedInfo.roomNum || !this.addBedInfo.bedNum) {
        // 弹出提示窗口
        ElMessage({
          showClose: true,
          message: '床位信息不能为空！',
          type: 'error',
        })
        return;
      }

      // 封装请求参数
      let postData = new URLSearchParams();
      postData.append("roomNum", this.addBedInfo.roomNum);
      postData.append("bedNum", this.addBedInfo.bedNum);
      postData.append("buildingName", this.buildingSelect);

      // 通过axios发送请求
      axios.post("/admin/bed/create", postData)
          .then(function (res) {
            switch (res.data.status) {
              case 10000:
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '添加成功！',
                  type: 'success',
                })
                location.reload();
                break;
              case 10008:
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '权限不够！',
                  type: 'error',
                })
                break;
              case 10023:
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '宿舍楼不存在！',
                  type: 'error',
                })
                break;
              case 10030:
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '宿舍不存在！',
                  type: 'error',
                })
                break;
              case 10031:
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '床位号已存在！',
                  type: 'error',
                })
                break;
            }
          })
    },

    /*
      添加床位Dialog
     */
    addBedDialog() {
      this.addBedDialogVisible = true;
    },

    /*
      更改楼栋选择
     */
    buildingChange() {

      let _this = this.$data;

      // 封装请求参数
      let postData = new URLSearchParams();
      postData.append("buildingName", _this.buildingSelect);

      // 通过axios发送请求，根据buildingName获取宿舍楼的所有房间信息
      axios.post("/admin/bed/selectByBuildingName", postData)
          .then(function (res) {
            _this.tableData = res.data.data;
            _this.pagination.total = res.data.data.length;
          })

    },
    /*
        退出登录
     */
    logout() {
      // 删除后端session
      axios.get("/admin/logout")
          .then(function(res) {
            console.log(res)
          })

      // 清除sessionStorage
      sessionStorage.clear();

      // 弹出提示窗口
      ElMessage({
        showClose: true,
        message: '账号已退出！',
        type: 'success',
      })

      // 跳转到登录页面
      this.$router.push("/admin/login");
    },

    /*
        更改当前页
     */
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
    }
  },

  mounted() {
    // 判断用户是否已经登录
    if (!sessionStorage.getItem('username')) {
      // 弹出提示窗口
      ElMessage({
        showClose: true,
        message: '请登录！',
        type: 'error',
      })
      // 路由跳转
      this.$router.push('/admin/login');
      return;
    }

    // 从sessionStorage获取用户名，赋值给data
    this.admin.username = sessionStorage.getItem("username");
    this.admin.role = sessionStorage.getItem("role");
    this.admin.buildingName = sessionStorage.getItem("buildingName")

    let that = this.$router;
    let _this = this.$data;

    // 通过axios查询所有宿舍楼信息
    axios.post('/admin/building/select')
        .then(function (res) {
          if (res.data.status == 10014) {
            // 弹出提示窗口
            ElMessage({
              showClose: true,
              message: '未登录，请重新登录！',
              type: 'error',
            })
            // 路由跳转
            that.push('/admin/login');
            return;
          }
          _this.buildingList = res.data.data;
          _this.pagination.total = res.data.data.length;
          if (_this.admin.role === '1') {
            _this.buildingSelect = _this.buildingList[0].buildingName;
          }
          if (_this.admin.role === '2') {
            _this.buildingSelect = _this.admin.buildingName;
          }

          if (_this.buildingSelect) {
            // 封装请求参数
            let postData = new URLSearchParams();
            postData.append("buildingName", _this.buildingSelect);

            // 通过axios发送请求，根据buildingName获取宿舍楼的所有房间信息
            axios.post("/admin/bed/selectByBuildingName", postData)
                .then(function (res) {
                  _this.tableData = res.data.data;
                  _this.pagination.total = res.data.data.length
                })
          }
        })


  },

  components: {
    Stamp,
    User,
    Grid,
    ArrowDown
  }
}
</script>

<style scoped>
.el-header, .el-footer {
  background-color: #b3c0d1;
  color: var(--el-text-color-primary);
  text-align: center;
  line-height: 60px;
}

.el-aside {
  background-color: #d3dce6;
  color: var(--el-text-color-primary);
  text-align: center;
  line-height: 200px;
}

.el-main {
  background-color: #e9eef3;
  color: var(--el-text-color-primary);
  text-align: center;
  margin: 0px;
  padding: 0px;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}

.el-header {
  width: 100%;
  height: 80px;
  display: block;
  line-height: 80px;
  padding-left: 50px;
}

.el-header .title {
  font-size: 20px;
  float: left;
  color: #303133;
}

.addStuBtn .el-button {
  float: left;
  margin: 10px 100px 10px 10px;
}

.footer .el-pagination {
  float: right;
  margin: 20px 30px 10px 10px;
}
</style>